import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { fetchCityList, fetchChangeCity } from './action';
import Loading from '../../components/Loading';
import CityList from './List';

class City extends Component {
  componentWillMount() {
    // 要求必须从/home页面进入
    !this.props.city && this.props.history.push('/home');
    this.props.fetchCityList();
  }

  handleBack = () => {
    const {history} = this.props;
    history.push('/home');
  }
  handleChangeCity = (index) => {
    const {fetchChangeCity, history} = this.props;
    fetchChangeCity(index).then(() => history.push('/home'));
  }

  render() {
    if(!this.props.cityList) {
      return <Loading/>
    }
    return (
      <CityList city={this.props.city} cityData={this.props.cityList} onClickIcon={this.handleBack}
        onClickItem={this.handleChangeCity}/>
    )
  }
}

export default withRouter(connect(state => ({
  city: state.home.city,
  cityList: state.city.cityList
}), {fetchCityList, fetchChangeCity})(City));
